package com.jxwifi.cloud.quickcleanserver.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.idroid.utils.NoDoubleClickListener;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.OrderFromBean;
import com.jxwifi.cloud.quickcleanserver.chronograph.ChronographActivity;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.jxwifi.cloud.quickcleanserver.utils.TokenTimeUtils;
import com.jxwifi.cloud.quickcleanserver.workmap.MapWorkActivity;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/5/13.
 */

public class WorkbenchListAdapter extends RecyclerView.Adapter {


    private Context mContext;
    private List<OrderFromBean> mList = new ArrayList<>();
    private String mTAG;
    private CountDownTimer timer;
    private String formatStr2;

    public WorkbenchListAdapter(Context ctx, String mTAG) {
        mContext = ctx;
        this.mTAG = mTAG;
    }

    /**
     * 下拉刷新时调用
     *
     * @param list
     */
    public void refresh(List<OrderFromBean> list) {
        mList.clear();
        addData(list);
    }

    public void updata() {
        mList.clear();
        notifyDataSetChanged();
    }

    //添加数据
    public void addData(List<OrderFromBean> list) {
        if (list.size() != 0 || list != null) {
            mList.addAll(list);
            notifyDataSetChanged();
        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.list_workbench_list_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        final ViewHolder mViewHolder = (ViewHolder) holder;
        final OrderFromBean mAskBean = mList.get(position);

        mViewHolder.mTvWorkbenchAddressText.setText(mAskBean.getProvince() + "" + mAskBean.getCity() + mAskBean.getArea() + "" + "" + mAskBean.getAddress());
        float mestimate = Float.valueOf(mAskBean.getPrices()) * mAskBean.getExpectHours();
        DecimalFormat myformat = new DecimalFormat("0.00");
        SpannableString styledText = new SpannableString("" + myformat.format(mestimate));
        styledText.setSpan(new TextAppearanceSpan(mContext, R.style.style0), 0, myformat.format(mestimate).indexOf(".") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(mContext, R.style.style1), myformat.format(mestimate).indexOf(".") + 1, myformat.format(mestimate).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mViewHolder.mTvListWorkbenchItemIncome.setText(styledText);
        //派单类型
        if (StateUtils.SYS.equals(mAskBean.getDispatchType())) {
            mViewHolder.mImgWorkbenchItemImages.setVisibility(View.GONE);
            mViewHolder.mImgWorkbenchItemImages.setText("");
        } else if (StateUtils.CLEAR_GRAB.equals(mAskBean.getDispatchType())) {
            mViewHolder.mImgWorkbenchItemImages.setVisibility(View.GONE);
            mViewHolder.mImgWorkbenchItemImages.setText("");
        } else if (StateUtils.Appoint.equals(mAskBean.getDispatchType())) {
            mViewHolder.mImgWorkbenchItemImages.setVisibility(View.VISIBLE);
            mViewHolder.mImgWorkbenchItemImages.setText("用户指定订单");
        } else if (StateUtils.SYS_MUST_DP.equals(mAskBean.getDispatchType())) {
            mViewHolder.mImgWorkbenchItemImages.setVisibility(View.VISIBLE);
            mViewHolder.mImgWorkbenchItemImages.setText("系统指定订单");
        }
        if (StateUtils.SER_START.equals(mAskBean.getOrderStatus())) {//已抢订单，还没出发
            mViewHolder.mTvWorkbenchTypeText.setText("未出发");
        } else if (StateUtils.SER_LEAVE.equals(mAskBean.getOrderStatus())) {//保洁员已出发
            mViewHolder.mTvWorkbenchTypeText.setText("已出发");
        } else if (StateUtils.SER_ARRIVE.equals(mAskBean.getOrderStatus())) {//保洁员到达
            mViewHolder.mTvWorkbenchTypeText.setText("已到达");
        } else if (StateUtils.SER_TIME_START.equals(mAskBean.getOrderStatus()) || StateUtils.SER_TIME_START_RE.equals(mAskBean.getOrderStatus())) {//开始计时 计时重新开始
            mViewHolder.mTvWorkbenchTypeText.setText("已开始");
        } else if (StateUtils.SER_TIME_STOP.equals(mAskBean.getOrderStatus())) {//计时暂停
            mViewHolder.mTvWorkbenchTypeText.setText("已暂停");
        }

        //如果状态是SER_TIME_START，SER_TIME_START_RE，SER_TIME_STOP这三种状态显示计时布局
        if (StateUtils.SER_TIME_START.equals(mAskBean.getOrderStatus()) ||
                StateUtils.SER_TIME_START_RE.equals(mAskBean.getOrderStatus()) ||
                StateUtils.SER_TIME_STOP.equals(mAskBean.getOrderStatus())) {

            mViewHolder.mLinWorkBenchTimeLayout.setVisibility(View.VISIBLE);
            mViewHolder.mLinWorkBenchTimeLayoutContent.setVisibility(View.GONE);
            //如果在已暂停的状态下请求一次时间数据，在其他状态下没过一分钟请求一次时间数据
            //获取一次数据
            initgettime(mList.get(0).getDeposit(),mList.get(0).getOrderCode(), mViewHolder.mTvWorkbenchUseTimeHours, mViewHolder.mTvWorkbenchUseTimeMines, mViewHolder.mTvWorkbenchIncomeText);
            if (StateUtils.SER_TIME_START.equals(mList.get(0).getOrderStatus()) || StateUtils.SER_TIME_START_RE.equals(mList.get(0).getOrderStatus())) {

                //开始倒计时，一分钟后刷新下数据（只对这个数据做刷新）
                getGapCount(mList.get(0).getDeposit(),60 * 1000, mList.get(0).getOrderCode(), mViewHolder.mTvWorkbenchUseTimeHours, mViewHolder.mTvWorkbenchUseTimeMines, mViewHolder.mTvWorkbenchIncomeText);
            }
        } else {
            mViewHolder.mLinWorkBenchTimeLayout.setVisibility(View.GONE);
            mViewHolder.mLinWorkBenchTimeLayoutContent.setVisibility(View.VISIBLE);
        }

        //在完成工作后，时间的方法需要注销掉，要不然会一直请求接口（判断第一条数据不为下面的三种状态，就注销）
        if (!StateUtils.SER_TIME_START.equals(mList.get(0).getOrderStatus()) && !StateUtils.SER_TIME_START_RE.equals(mList.get(0).getOrderStatus())) {
            getCloseTime();
        }

        //double disprovn = DistanceOfTwoPoints(LocationGaoDe.getLatitude(), LocationGaoDe.getLongitude(), Double.valueOf(mAskBean.getLat()), Double.valueOf(mAskBean.getLon())) / 1000;
        if (mAskBean.getRideDistance() > 1) {
            DecimalFormat format = new DecimalFormat("#0.00");
            String str = format.format(mAskBean.getRideDistance());
            mViewHolder.mTvListWorkbenchItemDistance.setText(str);
        } else {
            mViewHolder.mTvListWorkbenchItemDistance.setText("<1");
        }
        mViewHolder.mTvWorkbenchServiceTypeText.setText(mAskBean.getProductName());
        mViewHolder.mTvWorkbenchServiceTimeText.setText(mAskBean.getServiceTime());
        //换算时间  服务的时间为：serviceTime 系统时间：now TokenTimeUtils.newTime(mAskBean.getServiceTime(),mAskBean.getNow())
        String mServiceTime = TokenTimeUtils.newTime(mAskBean.getServiceTime(), mAskBean.getNow());
        if (mServiceTime.indexOf(":") != -1) {
            mViewHolder.mTvListRrderFromItemHours.setText("小时");
            mViewHolder.mTvListWorkbenchItemTime.setText(mServiceTime);
        } else {
            mViewHolder.mTvListRrderFromItemHours.setText("天");
            mViewHolder.mTvListWorkbenchItemTime.setText(mServiceTime);
        }

        mViewHolder.mLinWorkbenchLayout.setOnClickListener(new NoDoubleClickListener() {

            @Override
            protected void onNoDoubleClick(View v) {
                Intent intent = new Intent();
                if (StateUtils.SER_START.equals(mAskBean.getOrderStatus()) || StateUtils.SER_LEAVE.equals(mAskBean.getOrderStatus()) || StateUtils.SER_ARRIVE.equals(mAskBean.getOrderStatus())) {
                    intent.setClass(mContext, MapWorkActivity.class);
                    intent.putExtra("order_code", mAskBean.getOrderCode());
                    mContext.startActivity(intent);
                } else if (StateUtils.SER_TIME_START.equals(mAskBean.getOrderStatus()) || StateUtils.SER_TIME_START_RE.equals(mAskBean.getOrderStatus()) || StateUtils.SER_TIME_STOP.equals(mAskBean.getOrderStatus())) {
                    intent.setClass(mContext, ChronographActivity.class);
                    intent.putExtra("order_code", mAskBean.getOrderCode());
                    mContext.startActivity(intent);
                }


            }
        });
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        View mContainer;
        // LinearLayout mLinListFrgMainMessage;
        TextView mImgWorkbenchItemImages;//订单类型(系统指定，用户指定 无指定的隐藏)
        TextView mTvListWorkbenchItemTime;//时间
        TextView mTvListWorkbenchItemDistance;//公里
        TextView mTvListWorkbenchItemIncome;//价格
        TextView mTvWorkbenchServiceTypeText;//服务类型
        TextView mTvWorkbenchTypeText;//状态
        TextView mTvWorkbenchServiceTimeText;//服务时间
        TextView mTvWorkbenchAddressText;//地址
        LinearLayout mLinWorkbenchLayout;//整体布局
        TextView mTvListRrderFromItemHours;
        LinearLayout mLinWorkBenchTimeLayoutContent;//头部信息布局

        //计时布局
        LinearLayout mLinWorkBenchTimeLayout;//布局
        TextView mTvWorkbenchUseTimeHours;//小时
        TextView mTvWorkbenchUseTimeMines;//分钟
        TextView mTvWorkbenchIncomeText;//收入价格

        public ViewHolder(View itemView) {
            super(itemView);
            mContainer = itemView;
            mImgWorkbenchItemImages = (TextView) itemView.findViewById(R.id.tv_workbench_item_type);
            mTvListWorkbenchItemTime = (TextView) itemView.findViewById(R.id.tv_list_workbench_item_time);
            mTvListWorkbenchItemDistance = (TextView) itemView.findViewById(R.id.tv_list_workbench_item_distance);
            mTvListWorkbenchItemIncome = (TextView) itemView.findViewById(R.id.tv_list_workbench_item_income);
            mTvWorkbenchServiceTypeText = (TextView) itemView.findViewById(R.id.tv_workbench_service_type_text);
            mTvWorkbenchTypeText = (TextView) itemView.findViewById(R.id.tv_workbench_type_text);
            mTvWorkbenchServiceTimeText = (TextView) itemView.findViewById(R.id.tv_workbench_service_time_text);
            mTvWorkbenchAddressText = (TextView) itemView.findViewById(R.id.tv_workbench_address_text);
            mLinWorkbenchLayout = (LinearLayout) itemView.findViewById(R.id.lin_workbench_layout);
            mTvListRrderFromItemHours = (TextView) itemView.findViewById(R.id.tv_list_order_from_item_hours);
            mLinWorkBenchTimeLayoutContent = (LinearLayout) itemView.findViewById(R.id.lin_work_bench_time_layout_content);

            mLinWorkBenchTimeLayout = (LinearLayout) itemView.findViewById(R.id.lin_work_bench_time_layout);
            mTvWorkbenchUseTimeHours = (TextView) itemView.findViewById(R.id.tv_workbench_use_time_hours);
            mTvWorkbenchUseTimeMines = (TextView) itemView.findViewById(R.id.tv_workbench_use_time_mines);
            mTvWorkbenchIncomeText = (TextView) itemView.findViewById(R.id.tv_workbench_income_text);
        }
    }

    /**
     * 获取服务总时长和金额(每一分钟请求一次数据)
     *
     * @param ordercode 订单Code
     * @param hoursTV   小时
     * @param minesTV   分钟
     * @param priceTV   收入价格
     */
    public void initgettime(final String depost,String ordercode, final TextView hoursTV, final TextView minesTV, final TextView priceTV) {
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", ordercode);
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_GETTIME, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    JSONObject obj = JSON.parseObject(data);
                    String money = obj.getString("money");
                    long mtimes = obj.getLong("times");
                    String mServiceTime = TokenTimeUtils.change((int) mtimes);
                    String[] hoursmin = mServiceTime.split(":");
                    hoursTV.setText(hoursmin[0]);
                    minesTV.setText(hoursmin[1]);
                    if (Double.valueOf(money)>Double.valueOf(depost)){
                        priceTV.setText("" + money);
                    }else{
                        priceTV.setText("" + depost);
                    }
                } else {
                    PasswordLogin.passwordlogin(mContext, mTAG, AccountMgr.gettell(mContext), AccountMgr.getpassword(mContext));
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast =Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast,3000);
            }
        }, mTAG);
    }

    public void getGapCount(final String depost,final long Times, final String ordercode, final TextView hoursTV, final TextView minesTV, final TextView priceTV) {

        timer = new CountDownTimer(Times, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                initgettime(depost,ordercode, hoursTV, minesTV, priceTV);
                timer.start();
            }
        }.start();
    }

    public void getCloseTime() {
        Log.w("oushuhua", "CountDownTimer");
        if (timer != null)
            timer.cancel();
    }

    private static final double EARTH_RADIUS = 6378137;

    public static double DistanceOfTwoPoints(double lat1, double lng1,
                                             double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
}
